import React, { useEffect, useRef } from 'react';
import * as echarts from 'echarts';
import style from './styles.css';
import { CenterPage, CenterBottom } from '../centerPage/style';
import { ModuleTitle } from '../../style/globalStyledSet';
import { BorderBox13 } from '@jiaminghi/data-view-react';

import Map from '../centerPage/charts/Map';
import { connect } from 'dva';
import {
  RightPage,
  RightTopBox,
  RightCenterBox,
  RightBottomBox,
} from './style';

const ProjectDelivery = ({ data }) => {
  const trendChartRef = useRef(null);
  const compareChartRef = useRef(null);

  useEffect(() => {
    if (!data) return;

    // 1. 趋势图
    const trendChart = echarts.init(trendChartRef.current);
    trendChart.setOption({
      tooltip: {
        trigger: 'axis',
        formatter: function (params) {
          let result = `${params[0].name}<br/>`;
          params.forEach(param => {
            const seriesName = param.seriesName;
            const value = param.value;
            result += `${seriesName}: ${(value * 100).toFixed(2)}%<br/>`;
          });
          return result;
        }
      },
      legend: {
        type: 'scroll',
        orient: 'horizontal',

        data: [
          ...data.departments.map(dept => dept + '-项目文档交付率'),
          ...data.departments.map(dept => dept + '-工程文件交付率')
        ],
        textStyle: {  // 图例文本样式配置
          color: '#FFFFFF',          // 字体颜色（白色）
          // fontSize: 12,              // 字体大小（px）
          // fontWeight: 'normal',      // 字体粗细（normal|bold|bolder|lighter|100~900）
          // fontFamily: 'Arial',       // 字体类型
          // rich: {                    // 富文本样式（可选）
          //   highlight: {             // 自定义样式类
          //     color: '#FFD700',
          //     fontWeight: 'bold'
          //   }
          // }
        },
        pageTextStyle: {  // 分页按钮文字样式
          color: '#CCCCCC'
        }
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: data.months,
        axisLabel: {
          color: '#bad9ed',
        }
      },
      yAxis: {
        type: 'value',
        min: 0.7,
        max: 1,
        axisLabel: {
          color: '#bad9ed',
          formatter: function (value) {
            // 更安全的百分比格式化
            return (Math.round(value * 100 * 100) / 100) + '%';  // 保留两位小数
          }
        }
      },
      series: [
        ...data.docDelivery.trendSeries,
        ...data.fileDelivery.trendSeries
      ]
    });

    // 2. 对比图
    const compareChart = echarts.init(compareChartRef.current);
    compareChart.setOption({
      tooltip: {
        trigger: 'axis',
        formatter: function (params) {
          let result = `${params[0].name}<br/>`;
          params.forEach(param => {
            const seriesName = param.seriesName;
            const dataIndex = param.dataIndex;
            const dataSet = seriesName === '项目文档交付率' ?
              data.docDelivery.byDepartment[dataIndex] :
              data.fileDelivery.byDepartment[dataIndex];

            result += `${seriesName}: ${(param.value * 100).toFixed(2)}%<br/>`;
            if (seriesName === '项目文档交付率') {
              result += `已交付: ${dataSet.completed}份<br/>总需求: ${dataSet.total}份<br/>`;
            } else {
              result += `已交付: ${dataSet.completed}个<br/>总数: ${dataSet.total}个<br/>`;
            }
          });
          return result;
        },
        axisPointer: {
          type: 'shadow'
        }
      },
      legend: {
        data: ['项目文档交付率', '工程文件交付率'],
        textStyle: {
          color: '#bad9ed',
        },
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: data.departments,
        axisLabel: {
          color: '#bad9ed',
          interval: 0,
          rotate: 30
        }
      },
      yAxis: {
        type: 'value',
        min: 0,
        max: 1,
        axisLabel: {
          color: '#bad9ed',
          formatter: function (value) {
            // 更安全的百分比格式化
            return (Math.round(value * 100 * 100) / 100) + '%';  // 保留两位小数
          }
        }
      },
      series: [
        {
          name: '项目文档交付率',
          type: 'bar',
          data: data.docDelivery.byDepartment.map(item => item.value),
          itemStyle: {
            color: '#722ed1'
          }
        },
        {
          name: '工程文件交付率',
          type: 'bar',
          data: data.fileDelivery.byDepartment.map(item => item.value),
          itemStyle: {
            color: '#eb2f96'
          }
        }
      ]
    });

    return () => {
      trendChart.dispose();
      compareChart.dispose();
    };
  }, [data]);

  return (
    <RightPage>
      <br />
      <ModuleTitle >
        <i className='iconfont'>&#xe78f;</i>
        <span>项目交付</span>
      </ModuleTitle>
      <RightTopBox>
        <BorderBox13 className='right-bottom-borderBox13'>
          <br />
          <div className='right-top'>
            <ModuleTitle>
              &nbsp;&nbsp;&nbsp;&nbsp;
              <span>项目文档与工程文件交付率趋势</span>
            </ModuleTitle>
            <div className='right-top-content'>

              <div ref={trendChartRef} className={style["chart"]}></div>
            </div>
          </div>
        </BorderBox13>
      </RightTopBox>

      <RightCenterBox>
        <BorderBox13 className='left-bottom-borderBox13'>
        <br/>
          <div className={style["chart-container"]}>
            <ModuleTitle>
            &nbsp;&nbsp;&nbsp;&nbsp;
              <span>项目文档与工程文件交付率 - 事业部对比</span>
            </ModuleTitle>
            <br/>   <br/>
            <div ref={compareChartRef} className={style["chart"]}></div>
          </div>
        </BorderBox13>
      </RightCenterBox>
      <RightBottomBox>
      </RightBottomBox>
    </RightPage>
  );
};

export default ProjectDelivery;